<template>
  <div>
    <el-popover placement="top-start" title="最近十五天订单实付金额" :width="400" trigger="hover">
      <template #reference>
        <el-icon style="position: relative; z-index: 10;" color="#ffffff">
          <view />
        </el-icon>
      </template>
      <div>
        柱状图显示了最近十五天的订单实付金额分布。
      </div>
    </el-popover>
    <div ref="chartDom" id="chart-container" style="height: 600px;"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import axiosInstance from '@/api/axios';
import axios from "axios";

const chartDom = ref<HTMLElement | null>(null);

onMounted(async () => {
  await fetchData();
});

interface OrderListResponse {
  total: number;
  rows: {
    createBy: string;
    createTime: string;
    updateBy: string;
    updateTime: string;
    remark: string | null;
    id: number;
    userId: number;
    insId: number;
    payOrderNo: number | null;
    status: number;
    message: string;
    totalAmount: number;
    realAmount: number;
    discountAmount: number;
    payChannel: string;
    couponId: number | null;
    delFlag: number;
    payTime: string | null;
    closeTime: string | null;
    finishTime: string | null;
    refundTime: string | null;
  }[];
  code: number;
  msg: string;
}

async function fetchData() {
  try {
    const response = await axiosInstance.get('/order/order/list', {
      params: {
        startDate: new Date(new Date().setDate(new Date().getDate() - 90)).toISOString(),
        endDate: new Date().toISOString()
      }
    });

    if (!response || response.status!== 200) {
      console.error('API 请求失败，状态码：', response?.status);
      return;
    }

    const rawData = response.data.rows;
    if (!rawData ||!Array.isArray(rawData)) {
      console.error('API 响应数据为空或不是数组', rawData);
      return;
    }

    const filteredData = rawData.filter(item => item.status!== 1);
    const formattedData = formatData(filteredData);
    initChart(formattedData);
  } catch (error) {
    if (axios.isAxiosError(error)) {
      if (error.code === 'ERR_NETWORK') {
        console.error('网络连接出现问题，请检查网络设置。');
      } else {
        console.error('获取数据失败：', error.message);
      }
    } else {
      console.error('未知错误：', error);
    }
  }
}

function formatData(rawData) {
  const dateCountMap = new Map<string, { count: number; totalAmount: number }>();
  rawData.forEach(item => {
    const date = new Date(item.payTime).toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' });
    if (!dateCountMap.has(date)) {
      dateCountMap.set(date, { count: 1, totalAmount: item.realAmount });
    } else {
      const existingData = dateCountMap.get(date)!;
      existingData.count++;
      existingData.totalAmount += item.realAmount;
    }
  });

  return Array.from(dateCountMap.entries()).map(([date, { count, totalAmount }]) => {
    const value = (totalAmount / count).toFixed(2); // 平均金额
    return { date, value, count }; // 确保返回的对象包含 date, value, count
  });
}

function initChart(data) {
  const chartDomElement = document.getElementById('chart-container');
  if (!chartDomElement) {
    console.error('图表 DOM 未找到');
    return;
  }

  const myChart = echarts.init(chartDomElement);

  const option = {
    title: {
      text: '最近三月订单实付金额及笔数'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        // 确保 params 是数组，并且每个元素都有 data 属性
        let tooltipContent = '';
        params.forEach(param => {
          if (param && param.data) {
            const data = param.data;
            tooltipContent += `系列: ${param.seriesName}<br>日期: ${data.date}<br>实付金额: ${data.value} 元<br>订单笔数: ${data.count}<br>`;
          }
        });
        return tooltipContent || '无数据';
      }
    },
    legend: {
      data: ['实付金额', '订单笔数']
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: {
        rotate: 45, // 旋转标签，防止重叠
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '实付金额（元）',
        axisLabel: {
          formatter: '{value} 元', // 设置单位
          interval: 50 // 调整 Y 轴的间隔
        }
      },
      {
        type: 'value',
        name: '订单笔数',
        axisLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '实付金额',
        type: 'bar',
        data: data.map(item => parseFloat(item.value)),
        yAxisIndex: 0,
        label: {
          show: true, // 显示柱状图顶部的标签
          position: 'top', // 标签位置
          formatter: '{c} 元' // 标签格式
        }
      },
      {
        name: '订单笔数',
        type: 'line',
        data: data.map(item => item.count),
        yAxisIndex: 1
      }
    ]
  };

  myChart.setOption(option);
}
</script>

<style scoped>
/* 你可以在这里添加一些样式 */
</style>